<script setup lang="ts">
defineOptions({
  name: "echartsChart"
});
import { ref, onMounted, onUnmounted, computed, nextTick } from "vue";
// import { type UtilsEChartsOption } from "@pureadmin/utils";
// import type { EChartsOption } from "echarts/types/dist/shared";
import echartsCom from "../echartsCom/index.vue";
import modelTitle from "@/views/common/components/modelTitle/index.vue";
import { emitter } from "@/utils/mitt";
import { useRouterStoreHook } from "@/store/modules/router";
import type { UtilsEChartsOption } from "@pureadmin/utils";
import type { LabelLayoutFunctionType, EchartsInstanceFunctionType } from "@/views/common/components/types";
import { totalConsumption } from "@/api/modules/energy";

interface Props {
  /**  获取当前echarts实例对象，参数为实例对象和回调函数 */
  getEchartsInstance?: EchartsInstanceFunctionType | null;
  /**  获取 optiins 配置函数 */
  labelLayoutFn?: LabelLayoutFunctionType | null;
  /**  同 echarts option */
  options?: CommonEcharts.CommonEchartsOption | null;
  /**  有 title 时传入 */
  title?: string;
  /**  有按钮时传入，传入后会有 btn-click 事件 */
  button?: string;
  /**  title 栏右侧文字 */
  rightText?: string | number;
  /**  模块最低宽度，默认 330px */
  width?: number;
  /**  模块最低高度，默认 200px */
  height?: number;
  /**  是否需要背景阴影，默认为true */
  boxShadow?: boolean;
  /**  是否需要圆角，默认为true */
  borderRidus?: boolean;
  dictKey?: string;
  isSerch?: boolean;
  className?: string;
  energyType?: string;
  queryTimeType?: string;
  queryParams?: any;
  dateRange?: any;
}

const props = withDefaults(defineProps<Props>(), {
  width: 330,
  height: 200,
  boxShadow: true,
  borderRidus: true
});

interface Emits {
  /**  title 右侧按钮点击后触发 */
  (event: "btn-click"): void;
}

const emits = defineEmits<Emits>();

const echartsKey = ref<string>(Math.random().toString(36).slice(2, 10));
const echartsComRef = ref<InstanceType<typeof echartsCom> | null>(null);

const title_height = computed(() => (props.title ? "38px" : "0px"));
const min_width = computed(() => `${props.width}px`);
const min_height = computed(() => `${props.height}px`);

const clickHandler = () => emits("btn-click");

const updateEchartsKey = () => {
  emitter.on("viceMenuChange", () => {
    echartsKey.value = Math.random().toString(36).slice(2, 10);
  });
};

type itemStyleType = {
  [key: string]: string;
};

interface dataType {
  name: string;
  value: number;
  itemStyle?: itemStyleType;
}

const isWater = ref(false);
const routerStore = useRouterStoreHook();

const getParams = () => {
  const dictKeys = props.dictKey ? props.dictKey.split(",") : [];
  return {
    startTime: props.dateRange.length ? props.dateRange[0] : props.queryParams.startTime,
    endTime: props.dateRange.length ? props.dateRange[1] : props.queryParams.endTime,
    queryTimeGranularity: props.queryTimeType ? "" : props.queryParams.queryTimeGranularity,
    energyType: props.energyType,
    className: props.className,
    queryTimeType: props.queryTimeType,
    dictKey: dictKeys.length > 1 ? "" : props.dictKey
  };
};
// 总消耗
const labelLayoutTotalConsumeFn = async (ec: any) => {
  if (activeName.value === "HOT_WATER") {
    isWater.value = true;
  } else {
    isWater.value = false;
  }
  const title = props.title;
  const param = {
    className: routerStore.subject === "ALL" ? "" : routerStore.subject,
    energyType: activeName.value
  };
  const res: any = await totalConsumption(isWater.value, param);
  const data = res.equipmentRankingList.map(item => {
    const { consume_amount: value, eqp_1st_category_name: name } = item;
    return { value, name };
  });
  if (isWater.value) {
    return labelLayoutTotalWaterFn(ec, data, title);
  } else {
    return labelLayoutTotalFn(ec, data, title);
  }
};

const labelLayoutTotalWaterFn = (ec: any, data: Array<dataType>, title: string) => {
  const { getWidth } = ec;
  // labelLine长度
  const labelLayout = function (params) {
    const isLeft = params.labelRect.x < getWidth() / 2;
    const points = params.labelLinePoints;
    points[2][0] = isLeft ? params.labelRect.x : params.labelRect.x + params.labelRect.width;
    return { labelLinePoints: points };
  };
  const options: UtilsEChartsOption = {
    tooltip: {
      trigger: "item",
      formatter: "{b}: {c} ({d}%)"
    },
    legend: {
      data: ["Direct", "Marketing", "Search Engine", "Email", "Union Ads", "Video Ads", "Baidu", "Google", "Bing", "Others"]
    },
    series: [
      {
        name: "Access From",
        type: "pie",
        selectedMode: "single",
        radius: [0, "45%"],
        label: {
          position: "inner",
          fontSize: 14
        },
        labelLine: {
          show: false
        },
        itemStyle: {
          borderWidth: 2,
          borderColor: "#fff"
        },
        data: [
          { value: 700, name: "生产", itemStyle: { color: "#00e272" } },
          { value: 200, name: "生活", itemStyle: { color: "#2fe0ac" } },
          { value: 544, name: "厂务", itemStyle: { color: "#fe6a35" } }
        ]
      },
      {
        name: "Access From",
        type: "pie",
        radius: ["45%", "60%"],
        labelLine: {
          length: 30
        },
        label: {
          formatter: "{b|{b}} {per|{d}%}\n {c|{c}}{x|kw}  ",

          borderWidth: 1,
          borderRadius: 4,
          rich: {
            hr: {
              borderColor: "#8C8D8E",
              width: "100%",
              borderWidth: 1,
              height: 0
            },
            b: {
              color: "#4C5058",
              fontSize: 12,
              fontWeight: "bold",
              lineHeight: 20
            },
            per: {
              color: "#4C5058",
              padding: [3, 4],
              borderRadius: 4,
              fontWeight: "bold",
              fontSize: 12
            },
            c: {
              color: "#4C5058",
              fontSize: 12,
              fontWeight: "bold",
              lineHeight: 20
            },
            x: {
              color: "#4C5058",
              fontSize: 12,
              fontWeight: "bold",
              lineHeight: 20
            }
          }
        },
        itemStyle: {
          borderWidth: 2,
          borderColor: "#fff"
        },
        data: [
          { value: 100, name: "LIHTO", itemStyle: { color: "#30ffa0" } },
          { value: 100, name: "ETCH", itemStyle: { color: "#30ffa0" } },
          { value: 100, name: "CMP", itemStyle: { color: "#30ffa0" } },
          { value: 100, name: "WET", itemStyle: { color: "#30ffa0" } },
          { value: 100, name: "TF", itemStyle: { color: "#30ffa0" } },
          { value: 100, name: "DF", itemStyle: { color: "#30ffa0" } },
          { value: 100, name: "DM", itemStyle: { color: "#30ffa0" } },
          { value: 200, name: "Other", itemStyle: { color: "#60fffc" } },
          { value: 100, name: "电课", itemStyle: { color: "#ff9e68" } },
          { value: 222, name: "水课", itemStyle: { color: "#ff9e68" } },
          { value: 111, name: "气化课", itemStyle: { color: "#ff9e68" } },
          { value: 111, name: "机械课", itemStyle: { color: "#ff9e68" } }
        ]
      }
    ]
  };
  return options;
};
const labelLayoutTotalFn = (ec: any, data: Array<dataType>, title: string) => {
  const { getWidth } = ec;
  // labelLine长度
  const labelLayout = function (params) {
    const isLeft = params.labelRect.x < getWidth() / 2;
    const points = params.labelLinePoints;
    points[2][0] = isLeft ? params.labelRect.x : params.labelRect.x + params.labelRect.width;
    return { labelLinePoints: points };
  };
  const options: UtilsEChartsOption = {
    tooltip: {
      trigger: "item",
      formatter: "{b}: {c} ({d}%)"
    },
    legend: {
      data: ["Direct", "Marketing", "Search Engine", "Email", "Union Ads", "Video Ads", "Baidu", "Google", "Bing", "Others"]
    },
    series: [
      {
        name: "Access From",
        type: "pie",
        selectedMode: "single",
        radius: [0, "45%"],
        label: {
          position: "inner",
          fontSize: 14
        },
        labelLine: {
          show: false
        },
        itemStyle: {
          borderWidth: 2,
          borderColor: "#fff"
        },
        data: [
          { value: 700, name: "生产", itemStyle: { color: "#00e272" } },
          { value: 200, name: "生活", itemStyle: { color: "#2fe0ac" } },
          { value: 544, name: "厂务", itemStyle: { color: "#fe6a35" } }
        ]
      },
      {
        name: "Access From",
        type: "pie",
        radius: ["45%", "60%"],
        labelLine: {
          length: 30
        },
        label: {
          formatter: "{b|{b}} {per|{d}%}\n {c|{c}}{x|kw}  ",

          borderWidth: 1,
          borderRadius: 4,
          rich: {
            hr: {
              borderColor: "#8C8D8E",
              width: "100%",
              borderWidth: 1,
              height: 0
            },
            b: {
              color: "#4C5058",
              fontSize: 12,
              fontWeight: "bold",
              lineHeight: 20
            },
            per: {
              color: "#4C5058",
              padding: [3, 4],
              borderRadius: 4,
              fontWeight: "bold",
              fontSize: 12
            },
            c: {
              color: "#4C5058",
              fontSize: 12,
              fontWeight: "bold",
              lineHeight: 20
            },
            x: {
              color: "#4C5058",
              fontSize: 12,
              fontWeight: "bold",
              lineHeight: 20
            }
          }
        },
        itemStyle: {
          borderWidth: 2,
          borderColor: "#fff"
        },
        data: [
          { value: 100, name: "LIHTO", itemStyle: { color: "#30ffa0" } },
          { value: 100, name: "ETCH", itemStyle: { color: "#30ffa0" } },
          { value: 100, name: "CMP", itemStyle: { color: "#30ffa0" } },
          { value: 100, name: "WET", itemStyle: { color: "#30ffa0" } },
          { value: 100, name: "TF", itemStyle: { color: "#30ffa0" } },
          { value: 100, name: "DF", itemStyle: { color: "#30ffa0" } },
          { value: 100, name: "DM", itemStyle: { color: "#30ffa0" } },
          { value: 200, name: "Other", itemStyle: { color: "#60fffc" } },
          { value: 100, name: "电课", itemStyle: { color: "#ff9e68" } },
          { value: 222, name: "水课", itemStyle: { color: "#ff9e68" } },
          { value: 111, name: "气化课", itemStyle: { color: "#ff9e68" } },
          { value: 111, name: "机械课", itemStyle: { color: "#ff9e68" } }
        ]
      }
    ]
  };
  return options;
};

const getEcharts = async () => {
  await nextTick();
  return echartsComRef.value.getEcharts();
};

onMounted(async () => {
  updateEchartsKey();
});

onUnmounted(() => {
  emitter.off("viceMenuChange");
});

defineExpose({
  getEcharts
});
</script>

<template>
  <div class="echarts-chart" :class="{ boxShadow, borderRidus }">
    <modelTitle v-if="title" :title="title">
      <div class="model-title-slot">
        <span v-if="rightText" class="right-text">{{ rightText }}</span>
        <px-button v-if="button" type="primary" size="small" plain @click="clickHandler">{{ button }}</px-button>
      </div>
    </modelTitle>
    <div class="echarts-chart-com">
      <echartsCom ref="echartsComRef" :key="echartsKey" :getEchartsInstance="getEchartsInstance" :labelLayoutFn="labelLayoutFn" :options="options" />
    </div>
  </div>
</template>

<style lang="scss" scoped>
.echarts-chart {
  box-sizing: border-box;
  display: flex;
  flex-direction: column;
  gap: 6px;
  align-items: center;
  width: 100%;
  min-width: v-bind(min_width);
  height: 100%;
  min-height: v-bind(min_height);
  padding: 16px;
  background-color: #fff;

  .model-title-slot {
    display: flex;
    gap: 16px;
    align-items: center;

    .right-text {
      font-weight: 600;
      line-height: 1;
      color: var(--px-color-primary);
    }
  }

  .echarts-chart-com {
    display: flex;
    align-items: center;
    justify-content: center;
    width: 100%;
    height: calc(100% - v-bind(title_height));
  }
}

.boxShadow {
  box-shadow: 0 0 10px rgb(0 37 86 / 12%);
}

.borderRidus {
  border-radius: 4px;
}
</style>
